/**
 * @fileoverview This is a file where undefinedVars checks are disabled.
 * @suppress {undefinedVars}
 */
// the above is for the Google Closure Compiler ant task


function Environment() {
    this.ships = [];

    this.checkShips = checkShips;
    this.startGame = startGame;
    this.switchBoards = switchBoards;
    this.yourTurn = yourTurn;
    this.oppTurn = oppTurn;
    this.markCell = markCell;
    this.markSbCell = markSbCell;
//    this.finishGame = finishGame;


}


// initialize the environment
var env = new Environment();

$(document).ready(function(){

//    heartbeat();

    $("#valmis").click(function() {
        env.ships = ships_locations;
        checkIfAllShipsHaveBeenLocated();
        env.checkShips();
        return false;
    });

  //   This rotates ships 
    $("img[class^='ship']").click(function() {
    	var useIdForRotate=this.getAttribute("id");
        var useIdForRotate2= useIdForRotate[0];
        
        if (ships_map[useIdForRotate2].locatedInTable==0){
        	console.log(ships_map[useIdForRotate2].locatedInTable);
        	console.log("jouuuuu");
    	
        var cl = $(this).attr('class');
        console.log("the class is: " + cl);
        
        if (cl == 'ship') {
        	
            $(this).addClass('rotate90');
            if (this.getAttribute("src") == "images/2.png") {
            	
              useIdForRotate=this.getAttribute("id");
              useIdForRotate2= useIdForRotate[0];
              ships_map[useIdForRotate2].position = 1;
              console.log(ships_map[useIdForRotate2]);
                $(this).addClass('rotateLen2');
            } 
            else if (this.getAttribute("src") == "images/3.png") {
              useIdForRotate=this.getAttribute("id");
              useIdForRotate2= useIdForRotate[0];
              ships_map[useIdForRotate2].position = 1;
              console.log(ships_map[useIdForRotate2]);
                $(this).addClass('rotateLen3');
              
            } 
            else if (this.getAttribute("src") == "images/4.png") {
              useIdForRotate=this.getAttribute("id");
              useIdForRotate2= useIdForRotate[0];
              ships_map[useIdForRotate2].position = 1;
              console.log(ships_map[useIdForRotate2]);
                $(this).addClass('rotateLen4');
            }
        } 
        
        else if (cl == 'ship rotate90' || cl == 'ship rotate90 rotateLen2' || cl == 'ship rotate90 rotateLen3' || cl == 'ship rotate90 rotateLen4') {
            $(this).removeClass('rotate90');
            $(this).addClass('rotate180');
            ships_map[useIdForRotate2].position = 0;
            if (this.getAttribute("src") == "images/2.png") {
                $(this).removeClass('rotateLen2');
            } else if (this.getAttribute("src") == "images/3.png") {
                $(this).removeClass('rotateLen3');
            } else if (this.getAttribute("src") == "images/4.png") {
                $(this).removeClass('rotateLen4');
            }
        } else if (cl == 'ship rotate180') {
            $(this).removeClass('rotate180');
            ships_map[useIdForRotate2].position = 1;
            $(this).addClass('rotate270');
            if (this.getAttribute("src") == "images/2.png") {
                $(this).addClass('rotateLen2');
            } else if (this.getAttribute("src") == "images/3.png") {
                $(this).addClass('rotateLen3');
            } else if (this.getAttribute("src") == "images/4.png") {
                $(this).addClass('rotateLen4');
            }
        } else {
            $(this).removeClass('rotate270');
            ships_map[useIdForRotate2].position = 0;
            if (this.getAttribute("src") == "images/2.png") {
                $(this).removeClass('rotateLen2');
            } else if (this.getAttribute("src") == "images/3.png") {
                $(this).removeClass('rotateLen3');
            } else if (this.getAttribute("src") == "images/4.png") {
                $(this).removeClass('rotateLen4');
            }
        }
        
        }//kustuta
        else {
        	console.log("Kui laev on mänguväljal, siis teda enam pöörata ei saa");
        }
    });


    $("#replayOldGames").click(function() {
        document.location.replace("replayChoice.jsp");
    });

    $("#gameToLobby").click(function() {
        document.location.replace("lobby?id=" + localStorage.getItem("id"));
    });

    $("#gameToHS").click(function() {
        document.location.replace("highScoresTemp.jsp?id=" + localStorage.getItem("id"));
    });

    $("#logOutButton").click(function() {
//        $.get("logOut", {"id":localStorage.getItem("id")},
        $.get("logOut", {"token":localStorage.getItem("token")},
            function() {
                localStorage.removeItem("token");
				localStorage.removeItem("id");
                window.location.replace("login.jsp");
            });
    });


    /*
     var sbS = document.getElementById("main_board").rows[1].cells[2];
     var small = document.createElement('img');
     small.setAttribute("src","3.png");
     small.setAttribute("width", 94);
     small.setAttribute("height", 32);
     small.setAttribute("alt", "1-ruudu laev");
     small.setAttribute("title", "1-ruudu laev");
     small.removeAttribute("class");
     small.setAttribute("class", "ship rotate90");
     sbS.appendChild(small);
     console.log("appended");
     */

    //genBoard();
});


function checkShips() {
    // check if all ships are placed
		
    if (this.ships.length != 10) {
        alert("Kõik laevad ei ole paigutatud lauale.");
    } else {
        buff.sendShips(this.ships);
    }
}

function startGame() {

//    $.get("gameOver", {"id":localStorage.getItem("id")},
    $.get("gameOver", {"token":localStorage.getItem("token")},
    function(winner) {
        // alert tulemuse kohta
        if (winner == "you") {
            var sound = new Audio("sounds/applause.wav"); sound.play();
            alert("Palju õnne! Sa võitsid!");
        } else {
            var sound = new Audio("sounds/trombone.wav"); sound.play();
            alert("Kahjuks kaotasid.");
        }

        // salvesta mäng localstorage'sse
        savePlayers();
        savePlayedGames();

        // mine tagasi lobby'sse
//        document.location.replace("lobby?id=" + localStorage.getItem("id"));
        document.location.replace("lobby?token=" + localStorage.getItem("token"));
    });

    if (buff.startingPlayer) {
        alert("Mäng algab! Sina alustad.");
        this.switchBoards();
        $("#valmis").css("visibility", "hidden");
        //document.getElementById("valmis").setAttribute("display","none");
        //todo: pane käima funktsioon, mis pidevalt näitab, kelle kord on
        $("td.square").addClass("clickable");
        this.yourTurn();
    } else {
        alert("Mäng algab! Vastane alustab.");
        this.switchBoards();
        $("#valmis").css("visibility", "hidden");
        //document.getElementById("valmis").setAttribute("display","none");
        //todo: pane käima funktsioon, mis pidevalt näitab, kelle kord on
        $("td.square").addClass("unclickable");
        this.oppTurn();
    }
}

function yourTurn() {
    $("td.unclickable").addClass("clickable");
    $("td.unclickable").removeClass("unclickable");
    $("td.square").unbind("click");
    //console.log("made it clickable");
    $("td[class~='clickable']").click(function(event) {
        var cell = event.target;
        var y = cell.cellIndex;
        var x = cell.parentNode.rowIndex;
        var coords = [x,y];
        buff.shoot(coords);
    });
}

function oppTurn() {
    $("td.clickable").addClass("unclickable");
    $("td.clickable").removeClass("clickable");
    $("td.square").unbind("click");
    //console.log("made it unclickable");
    $("td[class~='unclickable']").click(function() {
        alert("Praegu pole sinu kord.");
    });

    buff.oppShoot();

    //singlePlayer
//    setTimeout("buff.oppShoot()",1000);
}

function markCell(coords, type) {
    var cell = document.getElementById("main_board").rows[parseInt(coords[0])].cells[parseInt(coords[1])];
    switch (type) {
        case 1:
            // the entire ship sank, mark the last cell to be shot
            console.log("ship sank");
            $(cell).append("<img src='images/explosion.png' title='explosion' alt='explosion' height='28px' width='28px' />");
            $(cell).addClass("checked");
//            var col = cell.cellIndex;
//            var row = cell.parentNode.rowIndex;
//            outer: for each (ship in buff.oppShips) {
//                for each (coord in ship) {
//                    if (row == coord[0] && col == coord[1]) {
//                        for each (cor in ship) {
//                            var c = document.getElementById("main_board").rows[cor[0]].cells[cor[1]];
//                            $(c).addClass("checked");
//                        }
//                        break outer;
//                    }
//                }
//            }
            break;
        case 2:
            console.log("ship hit");
            // the ship got hit, but didn't sink
            $(cell).append("<img src='images/explosion.png' title='explosion' alt='explosion' height='28px' width='28px' />");
            break;
        case 3:
            // it was a miss
            $(cell).append("<h3>X</h3>");
            console.log("marked cell");
            break;
        case 4:
            // cells that need to be coloured because the ship sank
            console.log("colouring cell");
            $(cell).addClass("checked");
            break;
        default:
            break;
    }
    // make it so that a cell can't be chosen twice
    $(cell).removeClass("clickable");
}


function markSbCell(coords, type) {
    var cell = document.getElementById("side_board").rows[parseInt(coords[0])].cells[parseInt(coords[1])];
    switch (type) {
        case 1:
            // the entire ship sank
            console.log("ship sank");
            $(cell).append("<img src='images/explosion.png' title='explosion' alt='explosion' height='13px' width='13px' />");
            $(cell).addClass("checked");
//            var col = cell.cellIndex;
//            var row = cell.parentNode.rowIndex;
//            outer: for each (ship in buff.ships) {
//                for each (coord in ship) {
//                    if (row == coord[0] && col == coord[1]) {
//                        for each (cor in ship) {
//                            var c = document.getElementById("side_board").rows[cor[0]].cells[cor[1]];
//                            $(c).css("background", "#12345f");
//                            //$(c).addClass("checked");
//                        }
//                        break outer;
//                    }
//                }
//            }
            break;
        case 2:
            console.log("ship hit");
            // the ship got hit, but didn't sink
            $(cell).append("<img src='images/explosion.png' title='explosion' alt='explosion' height='13px' width='13px' />");
            break;
        case 3:
            // it was a miss
            $(cell).append("<p>X</p>");
            break;
        case 4:
            // cells that need to be coloured because the ship sank
            console.log("colouring cell");
            $(cell).addClass("checked");
            break;
        default:
            break;
    }
}

//function finishGame(n) {
//    if (n == 0) {
//        alert("Mäng on läbi! Sa kaotasid.");
//    } else {
//        alert("Mäng on läbi! Sa võitsid!");
//    }
//    // cleanup
//
//}

function switchBoards() {

//    for each (var ship in this.ships) {
    for (var i = 0; i < this.ships.length; i++) {
        var ship = this.ships[i];

        //console.log("ship: " + ship);
        var attachPoint = ship[0];
        //console.log("attachpoint: " + attachPoint);
        var row = attachPoint[0];
        //console.log("row: " + row);
        var col = attachPoint[1];
        //console.log("col: " + col);
        var square = document.getElementById("main_board").rows[row].cells[col];

        /*
        var shipImg = square.innerHTML;
        var shipClass = $(shipImg).attr("class");
        var sbSquare = document.getElementById("side_board").rows[row].cells[col];
        // add ships to side board
        switch(ship.length) {
            case 1:
                var smallShip1 = document.createElement('img');
                smallShip1.setAttribute("src","1.png");
                smallShip1.setAttribute("width", 18);
                smallShip1.setAttribute("height", 18);
                smallShip1.setAttribute("alt", "1-ruudu laev");
                smallShip1.setAttribute("title", "1-ruudu laev");
                smallShip1.removeAttribute("class");
                smallShip1.setAttribute("class", shipClass);
                sbSquare.appendChild(smallShip1);
                break;
            case 2:
                var smallShip2 = document.createElement('img');
                smallShip2.setAttribute("src","2.png");
                smallShip2.setAttribute("width", 38);
                smallShip2.setAttribute("height", 18);
                smallShip2.setAttribute("alt", "2-ruudu laev");
                smallShip2.setAttribute("title", "2-ruudu laev");
                smallShip2.removeAttribute("class");
                smallShip2.setAttribute("class", shipClass);
                sbSquare.appendChild(smallShip2);
                break;

            case 3:
                var smallShip3 = document.createElement('img');
                smallShip3.setAttribute("src","3.png");
                smallShip3.setAttribute("width", 18);
                smallShip3.setAttribute("height", 58);
                smallShip3.setAttribute("alt", "3-ruudu laev");
                smallShip3.setAttribute("title", "3-ruudu laev");
                smallShip3.removeAttribute("class");
                smallShip3.setAttribute("class", shipClass);
                sbSquare.appendChild(smallShip3);
                break;
            case 4:
                var smallShip4 = document.createElement('img');
                smallShip4.setAttribute("src","4.png");
                smallShip4.setAttribute("width", 78);
                smallShip4.setAttribute("height", 18);
                smallShip4.setAttribute("alt", "4-ruudu laev");
                smallShip4.setAttribute("title", "4-ruudu laev");
                smallShip4.removeAttribute("class");
                smallShip4.setAttribute("class", shipClass);
                sbSquare.appendChild(smallShip4);
                break;
            default:
                console.error("A ship of length more than 4?! Preposterous!");
        }
        */

        var table = document.getElementById("side_board");
//        for each (coord in ship) {
        for (var i = 0; i < ship.length; i++) {
            var coord = ship[i];
            $(table.rows[coord[0]].cells[coord[1]]).css("background", "#555555");
        }




        // remove ships from main board
        square.innerHTML = "";



    }
}










// ------- TESTING -------





//env.ships = [[[1,2],[2,2],[3,2],[4,2]],[[4,4],[4,5],[4,6]],[[2,4],[2,5],[2,6]],[[1,7],[2,7]],[[1,9],[2,9]],[[4,7],[5,7]],[[4,9]],[[6,9]],[[6,2]],[[8,2]]];


/*
function genBoard() {
    <!--
    var corner = document.createElement("div");
    corner.setAttribute("class", "corner");

    var horizontalEdge = document.createElement("div");
    horizontalEdge.setAttribute("class", "hEdge");

    var verticalEdge = document.createElement("div");
    verticalEdge.setAttribute("class", "vEdge");

    var square = document.createElement("div");
    square.setAttribute("class", "square");
    -->

    var stage = document.getElementById("tableDiv");
    stage.innerHTML = "";
    var corner = "<div class='corner'></div>";
    $(stage).append(corner);
    for (var i = 1; i <= 10; i++) {
        var hEdge = $("<div class='hEdge'></div>");
        $(stage).append(hEdge);
    }
    $(stage).append(corner);
    for (var i =1; i <= 10; i++) {
        $(stage).append("<div class='vEdge'></div>");
        for (var j = 1; j <= 10; j++) {
            $(stage).append("<div class='square' ondrop='drop(event)' ondragover='allowDrop(event)'></div>");
        }
        $(stage).append("<div class='vEdge'></div>");
    }
    $(stage).append(corner);
    for (var i = 1; i <= 10; i++) {
        var hEdge = $("<div class='hEdge'></div>");
        $(stage).append(hEdge);
    }
    $(stage).append(corner);
}

*/






